# 读取本地行情数据
from IMDListener import IMDListener
from common.TickData import TickData


class LocalTickLoader(IMDListener):
    data_path = ''

    def set_data_path(self, path):
        self.data_path = path

    def run(self):
        last_tick_time = {}
        last_tick_volume = {}
        last_tick_amount = {}
        # 读入行情文本
        all_market_data = []
        with open(self.data_path, 'r', encoding='utf-8') as f:
            all_market_data = f.readlines()
        # 定义一个函数处理空字符
        to_float = lambda x: 0.0 if x == '' else float(x)
        # 对行情文本循环
        # datas = 0
        for line in all_market_data[1:]:
            line.replace('\n', '')
            md = line.split('\t')
            # 判断是否是重复tick数据
            if md[0] in last_tick_time.keys():
                if md[31] <= last_tick_time[md[0]]:
                    continue
            else:
                last_tick_volume[md[0]] = 0.0
                last_tick_amount[md[0]] = 0.0
            # 整理并发送新的数据
            mdit = iter(md)
            data = TickData()
            data.name = next(mdit)
            data.open = float(next(mdit))
            data.pre_close = float(next(mdit))
            data.price = float(next(mdit))
            data.high = float(next(mdit))
            data.low = float(next(mdit))
            data.bid = float(next(mdit))
            data.ask = float(next(mdit))
            data.volume = float(next(mdit))
            data.amount = float(next(mdit))
            data.b1_v = to_float(next(mdit))
            data.b1_p = float(next(mdit))
            data.b2_v = to_float(next(mdit))
            data.b2_p = float(next(mdit))
            data.b3_v = to_float(next(mdit))
            data.b3_p = float(next(mdit))
            data.b4_v = to_float(next(mdit))
            data.b4_p = float(next(mdit))
            data.b5_v = to_float(next(mdit))
            data.b5_p = float(next(mdit))
            data.a1_v = to_float(next(mdit))
            data.a1_p = float(next(mdit))
            data.a2_v = to_float(next(mdit))
            data.a2_p = float(next(mdit))
            data.a3_v = to_float(next(mdit))
            data.a3_p = float(next(mdit))
            data.a4_v = to_float(next(mdit))
            data.a4_p = float(next(mdit))
            data.a5_v = to_float(next(mdit))
            data.a5_p = float(next(mdit))
            data.date = next(mdit)
            data.time = next(mdit)
            data.inst_id = next(mdit)
            data.actual_time = next(mdit)
            # 更新tick时间、计算curVolume和curAmount
            last_tick_time[data.name] = data.time
            data.cur_volume = data.volume - last_tick_volume[data.name]
            data.cur_amount = data.amount - last_tick_amount[data.name]
            last_tick_volume[data.name] = data.volume
            last_tick_amount[data.name] = data.amount
            # 将行情推入原始行情队列
            self.md_queue.put(data)
        print('LocalTickLoader exit')
        # self.md_queue.put('SYSTEM_EXIT')
        return 0


